import 'package:html/parser.dart' show parse;
import 'package:http/http.dart' as http;
import '../models/article.dart';

abstract class ArticleCatcher {
  static var header = {
    'user-agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36'
  };

  static var meiriyiwenUri = Uri(scheme: "https", host: "www.meiriyiwen.com");

  static Future<Article?> getArticle() async {
    var response = await http.get(meiriyiwenUri, headers: header);
    if (response.statusCode == 200) {
      return getArticleContent(response.body);
    }
    return null;
  }

  static Article? getArticleContent(String resposenBody) {
    var dom = parse(resposenBody, encoding: 'utf-8');

    var articleElement = dom.querySelector("#article_show");
    if (articleElement == null) {
      return null;
    }

    var title = articleElement.querySelector("h1")?.text;
    if (title == null) {
      return null;
    }

    var author = articleElement.querySelector(".article_author")?.text;
    if (author == null) {
      return null;
    }

    var articleText = articleElement.querySelector(".article_text");
    if (articleText == null) {
      return null;
    }

    var content = '';

    for (var paragraph in articleText.querySelectorAll("p")) {
      var p = paragraph.text.trim();
      if (p.isEmpty){
        continue;
      }
      content = content + '\n\u3000\u3000' + p;
    }

    if (content.isEmpty) {
      return null;
    }

    return Article(title: title, author: author, content: content);
  }
}
